import selight
from selenium import webdriver
import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from pathlib import Path
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr



def send_email(title, text):
    # 发件人邮箱和授权码（不是邮箱登录密码）
    # sender_email = 'kang_fengjian@163.com'  # 替换为你的QQ邮箱
    sender_email = private_info["airport"]["send_email"]
    sender_code = private_info["airport"]["sender_code"]

    # 收件人邮箱
    for receiver_email in private_info["airport"]["reserve_email"]:
        # 构建邮件内容
        msg = MIMEText(text, 'plain', 'utf-8')  # 纯文本正文
        msg['From'] = formataddr(('康风建', sender_email))  # 发件人信息
        msg['To'] = formataddr(('收件人昵称', receiver_email))  # 收件人信息
        msg['Subject'] = title  # 邮件主题

        try:
            # 连接163邮箱的SMTP服务器（SSL加密）
            server = smtplib.SMTP_SSL('smtp.163.com', 465)
            # 登录邮箱
            server.login(sender_email, sender_code)
            # 发送邮件
            server.sendmail(sender_email, [receiver_email], msg.as_string())
            print('邮件发送成功！')
        except Exception as e:
            print(f'邮件发送失败: {e}')
        finally:
            # 关闭连接
            server.quit()

if __name__ == '__main__':    
    history = list()
    with open("private_info.json", "r", encoding="utf-8") as f:
        private_info = json.load(f)
    link = private_info["airport"]["link"]
    # 初始化
    chrome_option = Options()
    # chrome_option.set_capability("goog:loggingPrefs", {"performance": "ALL"})
    chrome_option.add_argument("--start-maximized")
    # chrome_option.add_argument("--headless")  # 无头模式，不打开浏览器窗口
    service = Service("./chromedriver/chromedriver.exe")
    driver = webdriver.Chrome(service=service, options=chrome_option)
    while True:
        formatted_time = datetime.now().strftime("%M")
        if formatted_time not in ['00', '30',]:
            time.sleep(50)
            continue
        driver.get(link)
        time.sleep(10)
        my_date = selight.get_text(driver, '//*[@id="calendar-scroll"]/li[@class="active"]')
        my_flight = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[2]/ul[1]/li')
        start_point = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[1]/div/div[1]/div[2]')
        end_point = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[1]/div/div[3]/div[2]')
        start_time = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[1]/div/div[1]/div[1]')
        end_time = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[1]/div/div[3]/div[1]')
        duration = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[1]/div[1]/div[1]/div/div[2]/div[1]/p')
        price = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[2]/div[1]/div[2]/div[1]')
        seat_type = selight.get_text(driver, '//*[@id="flight-content"]/div[6]/div/div[2]/div[1]/div[1]')
        formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        history.append((formatted_time, price))
        title = '【实时票价 {}】'.format(price)
        text = '{}实时票价：\n'.format(formatted_time)
        text += '{}({} -> {})\n'.format(my_flight, start_point.replace(' ', ''), end_point.replace(' ', ''))
        text += '{} {}-{} ({})\n'.format(my_date[:5], start_time, end_time, duration)
        text += '{} {}\n'.format(seat_type, price)
        text += link+'\n\n'
        text += '历史票价：\n'
        for i in history:
            text += '{} {}\n'.format(i[0], i[1])
        # print(text)
        
        if int(price[:-1]) < 2000:
            send_email(title, text)
        time.sleep(60)
    driver.close()